route.test.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // app/api/branches/[branch]/years/route.test.js
  2. import { describe, it, expect, beforeAll, afterAll } from "vitest";
  3. import fs from "node:fs/promises";
  4. import os from "node:os";
  5. import path from "node:path";
  6. import { GET as getYears } from "./route.js";
  7. let tmpRoot;
  8. beforeAll(async () => {
  9. tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "api-years-"));
  10. process.env.NAS_ROOT_PATH = tmpRoot;
  11. // tmpRoot/NL01/2024
  12. await fs.mkdir(path.join(tmpRoot, "NL01", "2024"), {
  13. recursive: true,
  14. });
  15. });
  16. afterAll(async () => {
  17. await fs.rm(tmpRoot, { recursive: true, force: true });
  18. });
  19. describe("GET /api/branches/[branch]/years", () => {
  20. it("returns years for a valid branch", async () => {
  21. const req = new Request("http://localhost/api/branches/NL01/years");
  22. // In Next.js 16, ctx.params is a Promise the framework would resolve.
  23. // In tests we simulate that.
  24. const ctx = {
  25. params: Promise.resolve({ branch: "NL01" }),
  26. };
  27. const res = await getYears(req, ctx);
  28. expect(res.status).toBe(200);
  29. const body = await res.json();
  30. expect(body).toEqual({
  31. branch: "NL01",
  32. years: ["2024"],
  33. });
  34. });
  35. it("returns 400 when branch param is missing", async () => {
  36. const req = new Request("http://localhost/api/branches/UNKNOWN/years");
  37. const ctx = {
  38. params: Promise.resolve({}), // no branch
  39. };
  40. const res = await getYears(req, ctx);
  41. expect(res.status).toBe(400);
  42. const body = await res.json();
  43. expect(body.error).toBe("branch Parameter fehlt");
  44. });
  45. it("returns 500 when NAS_ROOT_PATH is invalid", async () => {
  46. const originalRoot = process.env.NAS_ROOT_PATH;
  47. process.env.NAS_ROOT_PATH = path.join(tmpRoot, "does-not-exist");
  48. const req = new Request("http://localhost/api/branches/NL01/years");
  49. const ctx = {
  50. params: Promise.resolve({ branch: "NL01" }),
  51. };
  52. const res = await getYears(req, ctx);
  53. expect(res.status).toBe(500);
  54. const body = await res.json();
  55. expect(body.error).toContain("Fehler beim Lesen der Jahre:");
  56. process.env.NAS_ROOT_PATH = originalRoot;
  57. });
  58. });